package com.ifonly.common.typeconverter.impl;

import com.ifonly.common.typeconverter.Converter;
import com.ifonly.common.typeconverter.TypeConversionException;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-17 20:06
 * @since JDK 1.6
 */
public class ShortConverter implements Converter<Short> {
    @Override
    public Short convert(Object value) {
        if (value == null) {
            return null;
        }

        if (value.getClass() == Short.class) {
            return (Short) value;
        }
        if (value instanceof Number) {
            return ((Number) value).shortValue();
        }
        if (value instanceof Boolean) {
            return (Boolean) value ? Short.valueOf((short) 1) : Short.valueOf((short) 0);
        }

        try {
            String stringValue = value.toString().trim();
            return Short.valueOf(stringValue);
        } catch (NumberFormatException e) {
            throw new TypeConversionException(value, e);
        }
    }
}
